/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.openbookformat.heading;

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;
import org.openbookformat.project.HeadingPointer;
import org.openide.cookies.EditorCookie;
import org.openide.loaders.DataObject;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.util.lookup.Lookups;

/**
 *
 * @author MUFEED
 */
class HeadingrNode extends AbstractNode implements PropertyChangeListener {
    HeadingPointer pointer;

    public HeadingrNode(HeadingPointer pointer, DataObject dObj) {
        super(Children.LEAF, Lookups.fixed(new Object[] {
           pointer, dObj}) );
        this.pointer = pointer;
        pointer.addPropertyChangeListener(this);
    }

    public HeadingPointer getHeadingPointer() {
        return pointer;
    }

    @Override
    public String getDisplayName() {
        String idt = "";
        for(int i = 1; i < pointer.getLevel(); i++)
            idt += "        ";
        return idt + pointer.getHeading() + idt;// + "    - level -" + pointer.getLevel();
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        //fireDisplayNameChange(getDisplayName(), getDisplayName());
        setDisplayName(getDisplayName());
    }

    @Override
    public Action getPreferredAction() {
        return new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String out = JOptionPane.showInputDialog(null, "Chanage heading to:", 
                        pointer.getHeading());
                if (out != null && !out.equals(pointer.getHeading()))
                    pointer.setHeading(out);
//                bookProp.refreshHeadings();
            }
        };
    }

    @Override
    public Action[] getActions(boolean context) {
        return new Action[] {
            new GoToPointer()
        };
    }
    
    class GoToPointer extends AbstractAction {

        public GoToPointer() {
            super("Go to pointer location");
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            if(pointer.getOffset() == -1) {
                JOptionPane.showMessageDialog(null, "This heading points to nothing.");
            } else {
                EditorCookie ed = getLookup().lookup(DataObject.class).getCookie(
                        EditorCookie.class);
                if(ed != null) {
                    JEditorPane editorPane = ed.getOpenedPanes()[0];
                    editorPane.setCaretPosition(pointer.getOffset());
                }
            }
        }
    };

}
